//
//  Recruitment.m
//  HappyStore
//
//  Created by 点点充 on 16/1/20.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "Recruitment.h"
#import "RecruitmentShowCell.h"
#import "RecruitmentInfo.h"
#import "Preferens.h"
#import "UsedTool.h"
#import "Release_Job.h"

@interface Recruitment ()
{
    NSMutableArray *_aryInfo;
    NSInteger paggge;
    
    NSMutableDictionary *muDicParameters;
    
    NSString *strProjectId;
}
@end

@implementation Recruitment

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16.f],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"职位";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"发职位" style:UIBarButtonItemStylePlain target:self action:@selector(btnClickRight)];

    self.navigationItem.rightBarButtonItem = rightBar;
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    _aryInfo = [NSMutableArray array];
    paggge = 1;
    
    _mainTableView.backgroundColor = RGB(247, 247, 247);
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (_aryInfo.count != 0) {
            if ([[USER_DEFAULTS objectForKey:@"isOpenSound"] boolValue]) {//声音开关
                NSString *path = [[NSBundle mainBundle]pathForResource:@"refresh"
                                                                ofType:@"wav"];
                SystemSoundID soundID;
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
                AudioServicesPlaySystemSound(soundID); //仅播放音频
            }
            paggge = 1;
            [muDicParameters setObject:@"1" forKey:@"page"];
            [self startSearch];
        }else {
            [_mainTableView.mj_header endRefreshing];
        }
    }];
    
    
    
    _mainTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        paggge += 1;
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",(long)paggge] forKey:@"page"];
        [self startSearch];
    }];
    
    _mainTableView.mj_footer.hidden = YES;
    
    [[NSNotificationCenter defaultCenter]  addObserver:self
                                              selector:@selector(StartShaiXuanSearch:) name:@"StartShaiXuanRecruitment"
                                                object:nil];
    
    if (muDicParameters == nil) {
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:@"1" forKey:@"page"];
        [muDicParameters setObject:@"1" forKey:@"type"];
    }
    
    [self showRoundProgressWithTitle:@"请稍后..."];
    [self startSearch];
    
    self.mainSearchBar.layer.borderWidth = 1.f;
    self.mainSearchBar.layer.borderColor = [RGB(235, 235, 235) CGColor];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
}

- (void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)StartShaiXuanSearch:(NSNotification *)dic
{
    muDicParameters = [NSMutableDictionary dictionaryWithDictionary:dic.userInfo];//通过这个获取到传递的对象
    _aryInfo = [NSMutableArray array];
    [self startSearch];
    
}

/**
 *  @author LLJ, 16-01-16 17:01:06
 *
 *  rightBarClick
 */
- (void)btnClickRight
{
    
    
    if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {
        
        Release_Job *releaseVC = [[Release_Job alloc] initWithNibName:@"Release_Job" bundle:nil];
        [self.navigationController pushViewController:releaseVC animated:YES];
        
    }else{
        [SVProgressHUD showErrorWithStatus:@"请先登录!"];
        [SVProgressHUD dismissafterDelay:kHideHudDelay];
    }
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    if (_aryInfo.count != 0) {
        _aryInfo = [NSMutableArray array];
        [_mainTableView reloadData];
    }
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    //NSLog(@"%@",searchBar.text);
    
    if (searchBar.text.length == 0) {
        return YES;
    }else {
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",(long)paggge] forKey:@"page"];//页码
        [muDicParameters setObject:searchBar.text forKey:@"title"];//类型
        [self startSearch];
        return YES;
    }
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //NSLog(@"-----%@",searchBar.text);
    if (searchBar.text.length != 0) {
        [searchBar resignFirstResponder];
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",(long)paggge] forKey:@"page"];//页码
        [muDicParameters setObject:searchBar.text forKey:@"title"];//类型
        [self startSearch];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:_aryInfo.count];
    
    return _aryInfo.count+1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 45;
    }else{
        return 110;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row==0) {
        
        UITableViewCell *cell1 = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(screenW-30, 17, 10, 15)];
        imageView.image = [UIImage imageNamed:@"BackSingUp"];
        cell1.textLabel.font = [UIFont systemFontOfSize:16];
        cell1.textLabel.text = @"设置你的职位偏好";
        cell1.textLabel.textColor = RGB(23, 176, 216);
        [cell1 addSubview:imageView];
        return cell1;
        
    }else{

        static NSString *cellSingle = @"RecruitmentShowCell";
        UINib *nib = [UINib nibWithNibName:@"RecruitmentShowCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellSingle];
        RecruitmentShowCell *cell = [tableView dequeueReusableCellWithIdentifier:cellSingle];

        
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:_aryInfo[indexPath.row-1]];

    cell.titleLabel.text = dic[@"positionName"];
        
   //薪资
    cell.moneyLabel.text = [UsedTool moneyChange:dic[@"money"]];
        
    

    NSRange range = [dic[@"address"] rangeOfString:@"-"];
    cell.cityLabel.text = [dic[@"address"] substringToIndex:range.location];
        
    cell.schoolLabel.text = dic[@"schooling"];
    cell.yearLabel.text = dic[@"experience"];
    cell.addressLabel.text = dic[@"recruitCompany"];
    

    
    return cell;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    if (indexPath.row==0) {
        Preferens *preVC = [[Preferens alloc] initWithNibName:@"Preferens" bundle:nil];
        [self.navigationController pushViewController:preVC animated:YES];
    }else{
    RecruitmentInfo *recruVC = [[RecruitmentInfo alloc] initWithNibName:@"RecruitmentInfo" bundle:nil];
    recruVC.jobId = _aryInfo[indexPath.row-1][@"jobId"];
    [self.navigationController pushViewController:recruVC animated:YES];
    }

    
    
}

//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
//{
//    // segue.identifier：获取连线的ID
//    if ([segue.identifier isEqualToString:@"Recruitment_detail"]) {
//        Recruitment_Detail *result = segue.destinationViewController;
//        result.projectId = strProjectId;
//        if (_MainSegment.selectedSegmentIndex==0) {
//            result.strType = @"1";
//        }else {
//            result.strType = @"2";
//        }
//    }else if ([segue.identifier isEqualToString:@"pushRecruitmentShaiXuan"]) {
//        //筛选传值
//        Recruitment_Filter *filter = segue.destinationViewController;
//        if (_MainSegment.selectedSegmentIndex==0) {
//            filter.strType = @"1";
//        }else {
//            filter.strType = @"2";
//        }
//        
//    }
//}

#pragma mark - 请求任务
- (void)startSearch
{
    //page=页码&type=（1招聘 2求职）&title=根据名称&industry=根据行业&money=-根据金额，格式（0-5000000 亿以上：1000000000-亿）&address= 根据地区（格式：省-市-区 如果没有就：省-无-无）&experience=年限（1>一年以下 2>1-3年 3>3-5年 4>5-10年 5>10年以上 6>不限）
    
    NSString * str;
    
    if ([self.typeTitle isEqualToString:@"招聘求职"]) {
        
        str = @"getMyoutJobhunting_app_myHome.im";
        [muDicParameters setObject:self.userId forKey:@"userId"];//类型
        [muDicParameters setObject:self.userType forKey:@"userType"];//类型
        
    }else{
    
        str = @"getJobHunting_app_jobhunting.im";
    
    }
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,str];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//        NSLog(@"%@",dicInfo);
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            if (paggge == 1) {
                [_mainTableView.mj_header endRefreshing];
                
                _aryInfo = [NSMutableArray arrayWithArray:[dicInfo objectForKey:@"data"][@"record"]];
                
                if (_aryInfo.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }else {
                [_mainTableView.mj_footer endRefreshing];
                NSArray *ary11 = [dicInfo objectForKey:@"data"][@"record"];
                for (int i = 0; i<ary11.count; i++) {
                    NSDictionary *dic1 = ary11[i];
                    [_aryInfo addObject:dic1];
                }
                if (ary11.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }
            
            
            [_mainTableView reloadData];
            [self hideBubble];
        }else {
            _aryInfo = nil;
            [_mainTableView reloadData];
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];

            [self hideBubble];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [_mainTableView.mj_header endRefreshing];
        [_mainTableView.mj_footer endRefreshing];
        [self showSingleIconBubble:error.localizedDescription];

    }];
}





@end
